package org.xlp.db.xml;

import org.xlp.utils.ClassLoaderUtils;

import java.io.InputStream;

/**
 * 解析类路径下的sql配置文件处理器
 * @author xlp
 * @version 1.0
 */
public class ClassPathSQLXmlFileHandler extends AbstractSQLXmlFileHandler{
    /**
     * 类加载器
     */
    private ClassLoader classLoader;

    /**
     * 标记是类路径下的文件前缀
     */
    private final static String FILE_PATH_PREFIX = FilePathPrefixConstant.CLASS_PATH_PREFIX;

    public ClassPathSQLXmlFileHandler() {}

    public ClassPathSQLXmlFileHandler(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    /**
     * 获取类加载器
     * @return
     */
    public ClassLoader getClassLoader() {
        return classLoader;
    }

    /**
     * 设置类加载器
     * @param classLoader
     */
    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    /**
     * 把指定的文件描述路径转换成文件输入流
     *
     * @param sqlXmlFilePath
     * @return
     */
    @Override
    protected InputStream toInputStream(String sqlXmlFilePath) {
        sqlXmlFilePath = sqlXmlFilePath.substring(FILE_PATH_PREFIX.length());
        if (sqlXmlFilePath.startsWith("/") || sqlXmlFilePath.startsWith("\\")){
            sqlXmlFilePath = sqlXmlFilePath.substring(1);
        }
        if (classLoader == null){
            classLoader = ClassLoaderUtils.getDefaultClassLoader();
        }
        return classLoader.getResourceAsStream(sqlXmlFilePath);
    }

    /**
     * 判断给定的路径是否符合该sql配置文件解析器，进行解析
     *
     * @param sqlXmlFilePath
     * @return 返回 true：该解析器进行解析，false：则不进行解析，交给下一个解析器去解析
     * @see AbstractSQLXmlFileHandler#handle(String, ISQLXmlFileHandlerChain)
     */
    @Override
    protected boolean match(String sqlXmlFilePath) {
        return super.match(sqlXmlFilePath) && sqlXmlFilePath.startsWith(FILE_PATH_PREFIX);
    }
}
